#coding:utf-8
"""
*   TG_Coder : Dzlua
*   Email    : 505544956@qq.com
*   Time     : 2017/08/30
"""
#--------------------#
from flask import Flask, request, url_for, render_template
from flask_bootstrap import Bootstrap

from socket import *

#--------------------#
app = Flask(__name__, static_url_path='')
bs = Bootstrap(app)

#--------------------#
#--------------------#
@app.route('/')
def index():
    return app.send_static_file('index.html')

#----------#
@app.route('/so/', methods=['POST', 'GET'])
def so():
    if request.method == 'POST':
        lib = request.form.get('lib_name')
        content = request.form.get('search_text')
        page = int(request.form.get('search_page') or 1)
        #
        command,result = req_ser(lib, content, page)
        if result:
            return render_template('index.html', result=result, content=content,command=command, page=page,libname=lib)
    return render_template('index.html',page=1)

#--------------------#
#--------------------#
def req_ser(lib, content, page):
    if not lib or len(lib)<=0:
        return None,None
    if not content or len(content)<=0:
        return None,None
    #
    command = u'so\r\n' + content + '\r\n' + lib
    if page:
        command = command + u'\r\n%s' % page
    
    #
    try:
        addr = ('192.168.1.46', 1507)
        sock = socket(AF_INET, SOCK_STREAM)
        sock.connect(addr)
        sock.send(command.encode('utf-8'))
        result = sock.recv(65536)
        if not result:
            return result
        return command, str(result).decode('utf-8')
    except:
        return command, 'Error connect to server!'
#--------------------#
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1507, debug=True)

#--------------------#
